import {
	getPlayer,
	setInfo
} from '@/common/player'
import {
	getRandomIndex
} from '@/common/util'

import API from '@/common/apiUrl'
import {
	get
} from '@/common/api'

const playerInfoStorage = uni.getStorageSync('playerInfo')
const playerStatusStorage = uni.getStorageSync('playerStatus')
const playerQueueStorage = uni.getStorageSync('playerQueue')

export default {
	namespaced: true,
	state: {
		/**
		 * 歌曲是否正在加载
		 */
		loading: false,

		/**
		 * 播放队列
		 */
		queue: (playerQueueStorage || []),

		/**
		 * 当前播放歌曲信息
		 */
		playerInfo: (playerInfoStorage || {}),

		/**
		 * 播放器状态信息
		 */
		playerStatus: (playerStatusStorage || {
			currentTime: 0,
			duration: 0,
			paused: true,
			mode: 1
		}),

		/**
		 * 歌词滚动的定时器
		 */
		timer: undefined,
	},
	actions: {
		// 加载歌曲,store内自己调用
		load(context) {
			context.state.loading = true

			if (context.state.playerInfo.payload) {
				// 当存在播放记录，但播放器没有初始化src时  根据歌曲id获取url
				context.dispatch('getSongUrl', context.state.playerInfo.payload, {
					root: true
				}).then(url => {
					console.log("加载歌曲", url);
					context.state.loading = false
					//更新当前播放歌曲的信息
					if (url) setInfo({
						...context.state.playerInfo,
						url
					})
				})
			}
		},

		/**
		 * 选歌，获取歌曲信息
		 */
		setPlayerInfo({
			state,
			dispatch
		}, id) {
			state.loading = true

			// 如果上一首歌是插队列表的歌，把他的插队标记取消
			const curSongIdx = state.queue.findIndex(v => v.payload === state.playerInfo.payload)
			if (state.queue[curSongIdx]?.preference) {
				state.queue[curSongIdx].preference = false
			}
			uni.setStorageSync('playerQueue', state.queue)

			dispatch('getSongsDetail', [id], {
				root: true
			}).then(async (res) => {
				const songInfo = res[0]
				state.playerInfo = songInfo

				//同时获取歌词
				let geci = await get(API.SONG.GET_GECI, {
					id: id
				})
				let songLyric = geci.lrc.lyric
				//筛选出中括号里和外的
				let result = [];
				function formatTimeToSec(time){
					var arr = time.split(':');
					return (parseFloat(arr[0]) * 60 + parseFloat(arr[1])).toFixed(2);
				}
				songLyric.replace(/\[([^\]]+)\]([^\[]+)/g, function($0, $1, $2) {
					result.push({
						time: formatTimeToSec($1),
						lyric: $2
					});
				});
				console.log("获取到歌词", result);
				state.playerInfo.songLyric = result
				state.playerInfo.lyricIndex = 0

				uni.setStorageSync('playerInfo', songInfo)
				dispatch('load') //播放
			})
		},

		/**
		 * 更改播放器状态
		 * args: currentTime ?
			duration ?
			paused ?
			mode ?
		 */
		setPlayerStatus({
			state
		}, args) {
			Object.assign(state.playerStatus, args)
			const jsonPlayerStatus = JSON.parse(JSON.stringify(state.playerStatus))
			uni.setStorageSync('playerStatus', Object.assign(jsonPlayerStatus, {
				paused: true //暂停  
			}))
		},

		/**
		 * 开始播放
		 */
		setPlayerPlay({
			dispatch
		}) {
			console.log("开始");
			// #ifndef H5
			uni.vibrateShort({
				fail: (res) => {
					console.log("手机震动", res);
				}
			})
			// #endif

			const player = getPlayer()
			if (player?.src) player.play()
			else dispatch('load')
		},

		/**
		 * 歌词滚动
		 */
		listenLyricIndex({
			state
		}) {
			let bgAudioMannager = getPlayer()
			clearInterval(state.timer);
			state.timer = setInterval(() => {
				for (var i = 0; i < state.playerInfo.songLyric.length; i++) {
					//时间走到最后一位
					if (state.playerInfo.songLyric[state.playerInfo.songLyric.length - 1].time < bgAudioMannager.currentTime) {
						state.playerInfo.lyricIndex = state.playerInfo.songLyric.length - 1;
						break;
					}
					//当前时间大于前一位而小于后一位
					if (state.playerInfo.songLyric[i].time < bgAudioMannager.currentTime && state.playerInfo
						.songLyric[i + 1].time > bgAudioMannager.currentTime) {
						state.playerInfo.lyricIndex = i;
						console.log("歌词滚动", state.playerInfo.lyricIndex);
					}
				}
			}, 500);
		},
		cancelLyricIndex({
			state
		}) {
			clearInterval(state.timer);
		},

		/**
		 * 暂停播放
		 */
		setPlayerPause({
			dispatch
		}) {
			console.log("暂停");
			// #ifndef H5
			uni.vibrateShort({
				fail: () => {}
			});
			// #endif
			const player = getPlayer()
			if (player.src) player.pause()
			else dispatch('load')
		},

		/**
		 * 调整进度
		 */
		seek({
			dispatch
		}, time) {
			const player = getPlayer()
			if (player.src) {
				player.seek(time)
				player.play()
			} else {
				//调整歌曲事件时，歌曲在加载状态，等待加载完成后再设置
				uni.$once('onCanplay', () => player.seek(time))
				dispatch('load')
			}
		},

		/**
		 * 设置播放队列
		 */
		setQueue({
			state
		}, songList) {
			state.queue.push(...songList)
			uni.setStorageSync('playerQueue', state.queue)
		},
		/**
		 * 插播
		 */
		setPreference({
			state
		}, songList) {
			songList.forEach((song) => {
				//插播是从当前队列里找
				const curSongIdx = state.queue.findIndex(v => v.payload === song.payload)
				if (curSongIdx > -1) {
					state.queue[curSongIdx].preference = true
				} else {
					state.queue.unshift({
						...song,
						preference: true
					})
				}
			})

			uni.setStorageSync('playerQueue', state.queue)
		},

		/**
		 * 清空队列
		 */
		clearQueue({
			state
		}) {
			console.log("清空队列");
			state.queue = []
			uni.removeStorageSync('playerQueue')
			uni.showToast({
				title: '已清空队列',
				icon: 'none',
				duration: 2000
			})
		},

		/**
		 * 设置加载状态
		 */
		setLoading(status) {
			this.loading = status
		},

		// 切歌处理 setPlayerPrev, setPlayerNext
		changAirHandler({
			state
		}) {
			if (state.queue.length > 0) {
				// 有没有歌曲需要插队
				const preferenceList = state.queue.filter(v => {
					return v?.preference && v.payload !== state.playerInfo?.payload
				})
				if (preferenceList.length > 0) return preferenceList
				else return state.queue
			} else {
				uni.showToast({
					title: '代播清单为空',
					duration: 2000,
					icon: 'none'
				})
				return undefined
			}
		},

		// 上一首
		setPlayerPrev({
			state,
			dispatch
		}) {
			const list = dispatch('changAirHandler')
			if (list !== undefined) {
				const curSongId = state.playerInfo.payload
				const curSongIdx = list.findIndex(v => v.payload === curSongId)
				// 上 一首歌的下标
				const nextSongIdx = curSongIdx === 0 ? list.length - 1 : curSongIdx - 1
				const curSongPayload = list[nextSongIdx].payload
				dispatch('setPlayerInfo', curSongPayload)
			}
		},

		// 下一首
		async setPlayerNext({
			state,
			dispatch
		}) {
			const list = await dispatch('changAirHandler')
			console.log("切歌，当前播放队列", list);
			if (list !== undefined) {
				// 判断当前播放模式
				const curMode = state.playerStatus.mode
				// 队列长度
				const queueLength = list.length
				// 当前播放歌曲ID
				const curSongId = state.playerInfo.payload
				// 当前播放歌曲在队列中的下标
				const curSongIdx = list.findIndex(v => v.payload === curSongId)
				// 下一首歌的下标
				let nextSongIdx;
				if (curMode === 1) {
					// listRepeat列表循环
					nextSongIdx = curSongIdx >= queueLength - 1 ? 0 : curSongIdx + 1
				} else if (curMode === 2) {
					// list列表播放（播完即停）
					nextSongIdx = curSongIdx >= queueLength - 1 ? undefined : curSongIdx + 1
				} else if (curMode === 3) {
					// random随机播放
					nextSongIdx = getRandomIndex(0, queueLength - 1)
				} else if (curMode === 4) {
					// repeat单曲循环
					nextSongIdx = curSongIdx
				}

				// 开始切歌
				if (nextSongIdx !== undefined) {
					// 下一首歌的ID
					const nextSongId = list[nextSongIdx].payload
					dispatch('setPlayerInfo', nextSongId)
				} else {
					uni.showToast({
						title: '已经是最后一首了',
						duration: 2000,
						icon: 'none'
					})
				}
			}
		}
	}
}